<template>
  <el-menu
    :uniqueOpened="true"
    class="el-menu-vertical"
    @open="handleOpen"
    @close="handleClose"
    @select="selectChildMenu"
    background-color="#545c64"
    text-color="#fff"
    active-text-color="#ffd04b"
    :collapse="isCollapse"
    :router="true"
    :default-openeds="defaultOpeneds"
    :default-active="defaultActiveIndex"
  >
    <div class="logo">
      <img
        v-show="!isCollapse"
        src=""
        alt=""
      />
      <span v-show="isCollapse"><i class="el-icon-eleme"></i></span>
    </div>
    <template v-for="group of groupRouters" :key="group?.group">
      <el-submenu :index="group?.group" v-if="group?.path == null">
        <template #title>
          <i :class="group?.icon"></i>
          <span>{{ group?.title }}</span>
        </template>
        <template v-if="group?.children">
          <el-menu-item
            :route="routers"
            :index="routers?.name"
            v-for="routers of group?.children"
            :key="routers?.name"
          >
            <template #title>
              <i :class="routers?.meta?.icon"></i>
              <span>{{ routers?.meta?.title }}</span>
            </template>
          </el-menu-item>
        </template>
      </el-submenu>
      <el-menu-item v-else :route="group" :index="group?.group">
        <i :class="group?.icon"></i>
        <template #title>
          <span>{{ group?.title }}</span>
        </template>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<script lang="ts">
import { defineComponent, reactive, Ref, ref } from "vue";
import createSessionRouter from "@/router/handle";
import sessionStore from "store/storages/sessionStorage";
import { useStore } from "vuex";
import { onBeforeRouteUpdate, RouteLocationNormalizedLoaded } from "vue-router";

export default defineComponent({
  name: "AsideMenu",
  props: {
    isCollapse: {
      type: Boolean,
      default: false,
    },
  },
  setup() {
    // 从sesstionStorage里面获取登录时取得路由配置信息
    const groupRouters = createSessionRouter();
    // 面包屑导航
    const breadcrumb = ref();
    // store vuex
    const store = useStore();
    const defaultGroupIsPathNull = groupRouters[0]?.path === null;
    const defaultIndexActiove = defaultGroupIsPathNull
      ? groupRouters[0]?.children[0]?.name
      : groupRouters[0]?.group;
    // 默认打开的菜单组
    const defaultOpeneds = reactive(
      JSON.parse(
        sessionStore.read("defaultOpeneds") || `["${groupRouters[0]?.group}"]`
      )
    );
    // 默认激活的菜单项
    const indexActive = JSON.parse(
      sessionStore.read("defaultActiveIndex") || `"${defaultIndexActiove}"`
    );
    // 默认激活的菜单项，做一个判断，因为json转义""空字符串会报错；
    const defaultActiveIndex = ref(indexActive);
    // 处理菜单打开
    const handleOpen = function (key: string, keyPath: Array<string>) {
      // 设置默认菜单
      defaultOpeneds.value = keyPath;
      // 缓存到本地
      sessionStore.write("defaultOpeneds", JSON.stringify(keyPath));
    };
    // 处理当前选中的菜单项
    const selectChildMenu = function (index: string, indexPath: Array<string>) {
      defaultActiveIndex.value = index;
      // 这里由于示例的菜单数据只有两级，所以这里逻辑分开写
      if (indexPath.length == 1) {
        // 如果当前选中的是单独一个分组的菜单
        // 那就直接去找符合的菜单组
        const currentRouter = groupRouters.find((ele: any) => {
          return ele?.group == indexPath[0];
        });
        // 使用Vuex
        breadcrumb.value = [currentRouter.title];
        store.dispatch("CHANGEBREADCRUMB", breadcrumb.value);
      } else {
        // 否则就是菜单组里面包含子菜单的情况
        // 菜单组
        const groupTags = indexPath[0];
        // 菜单项
        const currentRouters = indexPath[1];
        // 把文字名称找出来
        groupRouters.forEach((ele: any) => {
          if (groupTags === ele.group) {
            ele.children.forEach((item: any) => {
              if (currentRouters === item.name) {
                breadcrumb.value = [ele.title, item.meta.title];
                // 设置菜单 actios
                store.dispatch("CHANGEBREADCRUMB", breadcrumb.value);
              }
            });
          }
        });
      }
      // 写入当前选中的菜单项，以确保当前侧边栏状态不发生改变
      sessionStore.write("defaultActiveIndex", JSON.stringify(index));
    };
    // 处理菜单组关闭
    const handleClose = function (key: string, keyPath: Array<string>) {
      // 和上面打开时一样处理
      defaultOpeneds.value = keyPath;
      sessionStore.write("defaultOpeneds", JSON.stringify(keyPath));
    };
    // 路由监听
    onBeforeRouteUpdate(
      (
        to: RouteLocationNormalizedLoaded,
        from: RouteLocationNormalizedLoaded,
        next: Function
      ) => {
        if (to?.meta?.group) {
          // 如果要去的路由存在group才进入
          // 找到当前要去到的路由
          const filtersRouter = groupRouters.find((ele: any) => {
            return to?.meta?.group === ele.group;
          });
          // 如果group的path不是null
          if (filtersRouter.path === null) {
            breadcrumb.value = [filtersRouter?.title, to?.meta?.title];
            defaultActiveIndex.value = to?.name;
            console.log(defaultActiveIndex.value);
            sessionStore.write(
              "defaultActiveIndex",
              JSON.stringify(defaultActiveIndex.value)
            );
          } else {
            breadcrumb.value = [filtersRouter?.title];
            defaultOpeneds.value = [filtersRouter?.group];
            defaultActiveIndex.value = filtersRouter?.group;
            console.log(defaultOpeneds.value);
            sessionStore.write(
              "defaultOpeneds",
              JSON.stringify(defaultOpeneds.value)
            );
            sessionStore.write(
              "defaultActiveIndex",
              JSON.stringify(defaultActiveIndex.value)
            );
          }
        }

        store.dispatch("CHANGEBREADCRUMB", breadcrumb.value);
        next();
      }
    );

    return {
      defaultOpeneds,
      defaultActiveIndex,
      groupRouters,
      handleOpen,
      handleClose,
      selectChildMenu,
    };
  },
});
</script>

<style  lang="less" scoped>
.el-menu {
  height: 100%;
}
.el-menu-item-group,
.el-menu,
.el-menu--inline {
  overflow: hidden;
}

.logo {
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 20px;
  img {
    height: 40px;
  }
}
.el-menu-vertical {
  height: 100vh;
  overflow-x: hidden;
  overflow-y: auto;
}
.el-menu-vertical:not(.el-menu--collapse) {
  width: 200px;
}
</style>